package net;

import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerSocketTest {

    @Test
    public void testServerSocket() throws IOException {
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("服务器:服务器启动成功,准备接收客户端请求");
        // 等待客户端请求,改方法会阻塞
        Socket socket = serverSocket.accept();
        if(socket!=null){
            InputStream inputStream = socket.getInputStream();
            byte[] buff = new byte[1024];
            int readLength = inputStream.read(buff);
            System.out.println("客户端请求的内容是:"+new String(buff, 0, readLength));

            //服务器给客户端相应数据
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("跟磊哥学习java不错".getBytes());
            System.out.println("服务器:服务器给客户端相应数据成功");
            socket.close(); //生产环境不使用
        }
    }


}
